package com.study.common.utils;

import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.net.*;
import java.util.Enumeration;

/**
 * @包名称 com.thrift.distributed.utils
 * @类描述 <pre> 获取本机IP地址</pre>
 * @作者 zhangbo
 * @创建时间 2019/9/19
 * @版本 1.00
 * @修改记录 <pre>
 *     版本           修改人         修改日期         修改内容描述
 *     -----------------------------------------------------------
 *     1.00           Lenovo        2019/9/19
 *     -----------------------------------------------------------
 * </pre>
 */
@Slf4j
public class NetAddressUtil {

    private NetAddressUtil() {
    }

    public static String getServerIp() {
        String serverIp = null;
        try {
            Enumeration<NetworkInterface> netInterfaces = NetworkInterface.getNetworkInterfaces();
            while (netInterfaces.hasMoreElements()) {
                NetworkInterface networkInterface = netInterfaces.nextElement();
                Enumeration<InetAddress> addresses = networkInterface.getInetAddresses();
                while (addresses.hasMoreElements()) {
                    InetAddress address = addresses.nextElement();
                    if (address instanceof Inet6Address) {
                        continue;
                    }
                    if (address.isSiteLocalAddress() && !address.isLoopbackAddress()) {
                        serverIp = address.getHostAddress();
                        log.debug("获取到本机IP地址：{}", serverIp);
                        return serverIp;
                    }
                }
            }
        } catch (SocketException e) {
            log.error("获取服务器IP地址错误");
        }
        return serverIp;
    }


    /**
     * 获取一个空闲的端口号
     *
     * @return
     */
    public static int getPort() {
        ServerSocket serverSocket = null; //读取空闲的可用端口
        try {
            serverSocket = new ServerSocket(0);
            final int port = serverSocket.getLocalPort();
            log.debug("本次获取的端口号为：{}", port);
            return port;
        } catch (IOException e) {
            log.error("获取端口异常：{}", e);
            return -1;
        } finally {
            if (null != serverSocket) {
                try {
                    serverSocket.close();
                } catch (IOException e) {
                    log.error("socket关闭异常");
                }
            }
        }
    }
}
